package net.fdukedom.epicurus.plugin;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import net.fdukedom.epicurus.domain.entity.Plugin;
import net.fdukedom.epicurus.domain.util.PluginHelper;
import net.fdukedom.epicurus.tools.logging.Logger;
import net.fdukedom.epicurus.tools.logging.WriterId;

/**
 * @author Alexander Kirakozov
 */
public class XMLPluginLoader extends AbstractPluginLoader {
    /**
     * String with xml plugins description
     */
    private String xmlPluginDescription;

    private Logger logger = Logger.getInstance(WriterId.PLUGIN_LOADER);

    public XMLPluginLoader(String xmlDescription) {
        this.xmlPluginDescription = xmlDescription;
    }

    @Override
    public List<Plugin> loadPlugins() {
        List<Plugin> plugins = new ArrayList<Plugin>();
        Map<String, Plugin> registredPlugins = PluginHelper.getInstance()
                .loadPluginsMap();
        SAXBuilder builder = new SAXBuilder();

        try {
            Document description = builder.build(new StringReader(xmlPluginDescription));
            List<Element> pluginElements = description.getRootElement().getChildren();

            for (Element pluginElement : pluginElements) {
                Plugin plugin = parsePlugin(pluginElement, registredPlugins);
                plugins.add(plugin);
            }
        } catch (JDOMException e) {
            logger.logError(
                    "Plug-in loading exception. Exception message: "
                            + e.getMessage());
        } catch (PluginParsingException e) {
            logger.logError(
                    "Plug-in loading exception. Exception message: "
                            + e.getMessage());
        } catch (IOException e) {
            logger.logError(
                    "Plug-in loading exception. Exception message: "
                            + e.getMessage());
        }
        return plugins;
    }
}
